﻿using Dapper;
using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.RBACs;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;
using MySql.Data.MySqlClient;
using System.Data;
using System.Security;

namespace RBAC.Write.API.Applications.PermissionsFiles
{
    public class RolesCreateHander : IRequestHandler<RolesCraeteCommand, ResultsDTO>
    {
        private readonly IBateRepository<Roles> roles;

        public RolesCreateHander(IBateRepository<Roles> roles)
        {
            this.roles = roles;
        }

        public async Task<ResultsDTO> Handle(RolesCraeteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ResultsDTO res = new ResultsDTO() { Code = 0 };
                DapperHelper dapper= new DapperHelper();
                Roles roles = new Roles()
                {
                    RolesId = 0,
                    RolesName=request.RolesName,
                    State=request.State
                };
                string sql1 = "insert into roles values(@RolesId,@RolesName,@State)";
                string sql2 = "insert into rolespermissions values(@RolesPermissionsId,@RolesId,@PermissionsId)";
                string sql3 = "select MAX(RolesId) FROM roles";
                using (MySqlConnection conn=new MySqlConnection(dapper.RBACWrite))
                {
                    conn.Open();
                    using (MySqlTransaction tran = conn.BeginTransaction())
                    {
                        try
                        {
                            res.Code +=await conn.ExecuteAsync(sql1, roles, tran);
                            var rolesId= conn.Query<int>(sql3, roles, tran).FirstOrDefault();
                            foreach (var item in request.Ids)
                            {
                                RolesPermissions rolesPermissions = new RolesPermissions()
                                {
                                    RolesPermissionsId = 0,
                                    RolesId= rolesId,
                                    PermissionsId=item
                                };
                                res.Code += await conn.ExecuteAsync(sql2, rolesPermissions,tran);
                            }
                            tran.Commit();
                        }
                        catch (Exception)
                        {
                            tran.Rollback();
                            throw;
                        }
                    }
                }
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
